<template>
  <div>
    <div class="tishi">
      {{ user.name }}{{$t('Container_Executetocontainerusingcommand')}}{{ user.command }}中。
      <el-button style="background: #067FB5; color: #fff;" size="small" @click="websocketBack">断开连接</el-button>
    </div>
    <div class="cmd" v-if="user">
      <div id="terminal"></div>
    </div>
  </div>
</template>

<script>
import 'xterm/dist/xterm.css'
import { Terminal } from 'xterm'
export default {
  data () {
    return {
      path: '',
      str: '', // websocket发送的请求
      id: ''
    }
  },
  props: ['user'],
  mounted () {
    // 进入cmd页面，创建url
    this.id = this.$route.params.id;
    let ip = ''
    if (localStorage.getItem('baseURL')) {
      ip = localStorage.getItem('baseURL').split('//')[1]
    }
    if (this.user.name === '') {
      // this.path = `ws://123.206.78.77:8080/ws?container=07adce022bcf&shell=${this.user.command}`
      this.path = `ws://${localStorage.getItem('baseURL') ? ip : location.host}/ws?container=${this.id}&shell=${this.user.command}`
    } else {
      this.path = `ws://${location.host}/ws?container=${this.id}&shell=${this.user.command}&user=${this.user.name}`
    }
    // 进入页面调用websocket建立连接
    this.socket()
  },
  methods: {
    // 告诉父组件，自己要断开连接
    websocketBack () {
      this.ws.close()
      this.$router.go(-1)
      // this.$emit('websocketBack')
    },

    // websocket
    socket () {
      this.ws = new WebSocket(this.path)
      // 创建cmd对象
      let xterm = new Terminal({
        rows: 25,
        cursorBlink: 5,
        scrollback: 30,
        tabStopWidth: 4,
        convertEol: true // 启用时，光标将设置为下一行的开头
      })
      xterm.open(document.getElementById('terminal'))
      // websocket错误的回调
      this.ws.onerror = () => {
        this.$message({
          showClose: true,
          message: '连接失败，请稍候重试！',
          type: 'error'
        })
        return this.$router.go(-1)
      }
      // 返回消息的回调
      this.ws.onmessage = function (event) {
        let reader = new FileReader()
        reader.onload = (event) => {
          let content = reader.result // 内容就在这里
          xterm.write(content)
        }
        reader.readAsText(event.data)
      }
      // socket连接成功
      this.ws.onopen = function () {
        // console.log('ws onopen ')
      }
      // 处理回车事件
      xterm.attachCustomKeyEventHandler(function (e) {
        if (e.keyCode === 13) {
          // console.log('enter')
          // ws.send('\r')
        }
      })
      // 发送消息。一个字符发一次。
      xterm.on('data', (data) => {
        // console.log('data xterm=>', data)
        // xterm.write(data)
        this.ws.send(data)
      })

      xterm.on('output', arrayBuffer => {
        // console.log('output===', arrayBuffer)
        xterm.write(arrayBuffer)
      })

      xterm.on('blur', arrayBuffer => {
        // console.log('blur===', arrayBuffer)
        xterm.write(arrayBuffer)
      })

      xterm.on('focus', arrayBuffer => {
        // console.log('focus===', arrayBuffer)
        xterm.write(arrayBuffer)
      })

      xterm.on('keydown', arrayBuffer => {
        // console.log('keydown===', arrayBuffer)
        xterm.write(arrayBuffer)
      })

      xterm.on('lineFeed', arrayBuffer => {
        // console.log('lineFeed===', arrayBuffer)
        xterm.write(arrayBuffer)
      })

      xterm.on('resize', size => {
        this.ws.send('resize', [size.cols, size.rows])
        // console.log('resize', [size.cols, size.rows])
      })
    }
  },
  beforeDestroy () {
    this.ws.close()
  }
}
</script>

<style lang="scss" scoped>
.tishi{
  font-size: 18px;
}
.cmd{
  margin-top: 20px;
}
</style>
